package com.fyyg.common.util.logistic;

import java.util.HashMap;

import com.fyyg.common.util.logistic.pojo.LogisticCode;
import com.fyyg.common.util.logistic.pojo.TaskRequest;
import com.fyyg.common.util.logistic.pojo.TaskResponse;

/**
 * 物流信息订阅
 * @author CHENYI
 *
 */
public class LogisticSubscribe {

	public static void main(String[] args){
		String company = "yuantong";
		String number = "560349682378";
		String form = "上海浦东新区";
		String to = "广东深圳南山区";
		subscribe(company, number, null, null);
	}
	
	
	/***
	 * 物流信息订阅
	 * @param company 物流公司编码
	 * @param number 物流单号
	 * @param form  发货地址
	 * @param to	收获地址
	 * @return
	 */
	public static boolean subscribe(String company,String number,String form,String to){
		TaskRequest req = new TaskRequest();
		req.setCompany(company);
		req.setFrom(form);
		req.setTo(to);
		req.setNumber(number);
		req.getParameters().put("callbackurl", LogisticCode.CALL_BACK_URL);
		req.setKey(LogisticCode.APP_KEY);
		
		HashMap<String, String> p = new HashMap<String, String>(); 
		p.put("schema", LogisticCode.SCHEMA);
		p.put("param", JacksonHelper.toJSON(req));
		try {
			String ret = HttpRequest.postData(LogisticCode.POST_SUBSCRIBE_URL, p, "UTF-8");
			TaskResponse resp = JacksonHelper.fromJSON(ret, TaskResponse.class);
			if(resp.getResult()==true){
				return resp.getResult();
			}else{
				//System.out.println("订阅失败:"+resp.getMessage()+";错误编码："+resp.getReturnCode());
				if(null != resp.getReturnCode() && "500".equals(resp.getReturnCode())){
					return suberRepeat(company, number, form, to);
				}else{
					return resp.getResult();
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	//重复提交一次
	public static boolean suberRepeat(String company,String number,String form,String to){
		TaskRequest req = new TaskRequest();
		req.setCompany(company);
		req.setFrom(form);
		req.setTo(to);
		req.setNumber(number);
		req.getParameters().put("callbackurl", LogisticCode.CALL_BACK_URL);
		req.setKey(LogisticCode.APP_KEY);
		
		HashMap<String, String> p = new HashMap<String, String>(); 
		p.put("schema", LogisticCode.SCHEMA);
		p.put("param", JacksonHelper.toJSON(req));
		try {
			String ret = HttpRequest.postData(LogisticCode.POST_SUBSCRIBE_URL, p, "UTF-8");
			TaskResponse resp = JacksonHelper.fromJSON(ret, TaskResponse.class);
			/*if(resp.getResult()==true){
				System.out.println("订阅成功");
			}else{
				System.out.println("订阅失败:"+resp.getMessage()+";错误编码："+resp.getReturnCode());
			}*/
			return resp.getResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	
}
